package cn.e2win.base.controller;

import java.sql.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e2win.base.entity.BaseEntity;
import cn.e2win.base.entity.SysUser;
import cn.e2win.base.json.vo.Pager;
import cn.e2win.base.json.vo.Result;
import cn.e2win.base.service.BaseMvcServiceIf;
import cn.e2win.biz.annotation.PageParam;
import cn.e2win.biz.sys.Dict;


public abstract class BaseController<T extends BaseEntity, PK extends Integer> extends CommonExceptionController implements BaseControllerIf<T, PK>, InitializingBean{
	
	public static final String IDS = "ids";
	public static final String ID = "id";
	public static final String ENTITY = "entity";
	public static final String FUNID = "funId";
	public static final String MODULE = "module";
	public static final String OBJECT = "object";
	public static final String ITEMS = "items.";
	
	public static final String USER = "user";
	
	
	private BaseMvcServiceIf<T, PK> service;

	public abstract BaseMvcServiceIf<T, PK> initService();
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		this.service = initService();
		
	}
	/*
	@RequestMapping("toAdd")
	public String toAdd(@RequestParam(ENTITY) String entity){
		return entity + "/add";
	}
	@RequestMapping("toUpdate/{id}")
	public String toUpdate(@PathVariable(ID) PK id, @RequestParam(ENTITY) String entity, ModelMap modelMap){
		try {
			T obj = service.get(id);
			modelMap.put(OBJECT, obj);
			return entity + "/update";
		} catch (Exception e) {
			logger.error(e);
			return "msg/common/fail";
		}
	}*/

	@RequestMapping("toEdit/{id}")
	public String toEdit(HttpServletRequest request, @PathVariable(ID) PK id, ModelMap modelMap){
		T obj = service.get(id);
		modelMap.put(OBJECT, obj);
		if(Dict.getRealPath()==null){
			Dict.setRealPath(request.getSession().getServletContext().getRealPath("/"));
		}
		String[] path = request.getServletPath().split("/");
		String module = path[1];
		String entity = path[2];
		modelMap.put(MODULE, module);
		modelMap.put(ENTITY, entity);
		return module+ "/" + entity + "Edit";
	}

	
	
	/*@RequestMapping("add")
	@ResponseBody
	public Result add(HttpServletRequest request,@ModelAttribute T obj, @RequestParam(ENTITY) String entity){	
		Result r = new Result();//通过@ResponseBody注解把object转为json
		try {
			SysUser user = (SysUser)request.getSession().getAttribute(USER);
			service.save(obj, user);
			r.setCallbackType(Result.CLOSE_CURRENT);
			r.setNavTabId("listView_"+entity);//main.jsp中的tab,当这个tab为reloadFlag=1时,会被自动加载
			return r;
		} catch (Exception e) {
			logger.error(e);
			r.setStatusCode(Result.FAILED);
			return r;
		}
	}
	@RequestMapping("update")
	@ResponseBody
	public Result update(HttpServletRequest request,@ModelAttribute T obj, @RequestParam(ENTITY) String entity){
		Result r = new Result();
		try {
			SysUser user = (SysUser)request.getSession().getAttribute(USER);
			service.update(obj,user);
			r.setCallbackType(Result.CLOSE_CURRENT);
			r.setNavTabId("listView_"+entity);
			return r;
		} catch (Exception e) {
			logger.error(e);
			r.setStatusCode(Result.FAILED);
			r.setCallbackType(Result.CLOSE_CURRENT);
			r.setNavTabId("listView_"+entity);
			return r;
		}
	}*/
	@RequestMapping("edit")
	@ResponseBody
	public Result edit(HttpServletRequest request,@ModelAttribute T obj,ModelMap modelMap){
		Result r = new Result();
		
		SysUser user =  getContextUser();;
		service.update(obj,user);
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));//main.jsp中的tab,当这个tab为reloadFlag=1时,会被自动加载
		return r;
			
	}
	
	
	@RequestMapping("delete/{id}")
	@ResponseBody
	public Result delete(HttpServletRequest request,@PathVariable(ID) PK id){
		Result r = new Result();
	    service.delete(id);
		String[] path = request.getServletPath().split("/");
		String module = path[1];
		String entity = path[2];
		//r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+entity);//main.jsp中的tab,当这个tab为reloadFlag=1时,会被自动加载
	    return r;
	}
	
	
	@RequestMapping("batchDel")
	@ResponseBody
	public Result batchDel(HttpServletRequest request,@RequestParam(IDS) PK[] keies){
		Result r = new Result();
		service.delete(keies);
		String[] path = request.getServletPath().split("/");
		String module = path[1];
		String entity = path[2];
		//r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+entity);//main.jsp中的tab,当这个tab为reloadFlag=1时,会被自动加载
		return r;
	}

	@RequestMapping("list")
	public String list(HttpServletRequest request, @PageParam Pager pager, ModelMap modelMap){
		service.pageList(pager);
		modelMap.put("pager", pager);
		String[] path = request.getServletPath().split("/");
		String module = path[1];
		String entity = path[2];
		modelMap.put(MODULE, module);
		modelMap.put(ENTITY, entity);
		return module+ "/" + entity + "List";
	}
	
	/**
	 * get login user from spring scurity context 
	 * @return
	 */
	public static SysUser getContextUser() {
	    Authentication  authentication =  SecurityContextHolder.getContext().getAuthentication();
	    WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();
	    logger.debug("remote ip address is: " + webAuthenticationDetails.getRemoteAddress());
	    logger.debug("remote session is: " + webAuthenticationDetails.getSessionId());
	   
	    SysUser user = (SysUser)authentication.getPrincipal();
	    logger.debug("user id: " + user.getId());
	    return user;

	}

	@InitBinder
    public void initDataBinder(WebDataBinder binder) {
        TimeEditor timeEditor = new TimeEditor();
        //也可以是日期格式：timeEditor.setFormat("yyyy-MM-dd");
        //但必须与页面input的handleTime输入框格式一致，否则保存指定的日期会失败。
        binder.registerCustomEditor(Date.class, "handleTime", timeEditor);
         //其他方法
        //DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        //CustomDateEditor dateEditor = new CustomDateEditor(fmt, true); 
        //binder.registerCustomEditor(Date.class, dateEditor); 
        //super.initBinder(request, binder);    
    }
	 
	@ModelAttribute
	public void initParam(HttpServletRequest request,ModelMap modelMap) {
		modelMap.put(FUNID, "");
		
	}
}
